package bzapps.weynak;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpParams;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.location.Location;
import android.util.Log;

public class ClientOperations {

    public static final String HOST = "http://www.bz-apps.com/weynak";

    private static final String UIDS_URI = HOST + "/friends.php?manage_friends=retrieve_friends";
    
    private static final String SAVE_NOTE = HOST + "/notes.php?note=save";
    
    private static final String GET_NOTES = HOST + "/notes.php?note=retrieve_all";
    
    private static final String GET_MY_NOTES = HOST + "/notes.php?note=retrieve_mine";

    private static final String GET_PHOTOS = HOST + "/photos.php?photo=retrieve_all";
    
    private static final String GET_MY_PHOTOS = HOST + "/photos.php?photo=retrieve_mine";
    
    private static final String UPDATE_URI = HOST + "/locations.php?loc=update";
    
    private static final String REGISTER_PUSH = HOST + "/push_settings.php?action=register";
    
    private static HttpParams params = new BasicHttpParams();

    static {
       
    }

    private ClientOperations()
    {
    }
    

    public static ArrayList<Friend> getFriends(String myUid) throws ClientProtocolException, IOException, JSONException
    {
    	ArrayList<Friend> data = new ArrayList<Friend>();
    	HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(UIDS_URI);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("uid", myUid));
        post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
        	
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            JSONObject json_data = null;
			for (int i = 0; i < result.length(); i++) {
				Friend f = new Friend();
				json_data = result.getJSONObject(i);
				f.id = json_data.getString("uid");
				f.first_name = json_data.getString("fname");
				f.last_name = json_data.getString("lname");
				f.lat = json_data.getDouble("latitude");
				f.lon = json_data.getDouble("longitude");
				f.picture = json_data.getString("picture");
				f.date = json_data.getString("last_date");
				data.add(f);
				}
			
        }		
        return data;
    }
    
    public static ArrayList<Note> getMyNotes(String myUid) throws ClientProtocolException, IOException, JSONException
    {
    	Log.w("WEYNAK.getmynotes", "fetfiyaaaaaaaaaaaaa");
    	ArrayList<Note> data = new ArrayList<Note>();
    	HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(GET_MY_NOTES);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("uid", myUid));
        post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
        	
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            JSONObject json_data = null;
			for (int i = 0; i < result.length(); i++) {
				Note n = new Note();
				json_data = result.getJSONObject(i);
				n.uid = myUid;
				n.fname = json_data.getString("fname");
				n.lname = json_data.getString("lname");
				n.title = json_data.getString("title");
				n.desc = json_data.getString("desc");
				n.lat = json_data.getDouble("latitude");
				n.lon = json_data.getDouble("longitude");
				n.date = json_data.getString("action_date");
				data.add(n);
				}
        }		
        return data;
    }
    
    public static ArrayList<Note> getNotes(String myUid) throws ClientProtocolException, IOException, JSONException
    {
    	Log.w("WEYNAK.getnotes", "fetfiyaaaaaaaaaaaaa");
    	ArrayList<Note> data = new ArrayList<Note>();
    	HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(GET_NOTES);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("uid", myUid));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
        	
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            JSONObject json_data = null;
			for (int i = 0; i < result.length(); i++) {
				Note n = new Note();
				json_data = result.getJSONObject(i);
				n.fname = json_data.getString("fname");
				n.lname = json_data.getString("lname");
				n.title = json_data.getString("title");
				n.desc = json_data.getString("desc");
				n.lat = json_data.getDouble("latitude");
				n.lon = json_data.getDouble("longitude");
				n.date = json_data.getString("action_date");
				data.add(n);
				}
        }		
        return data;
    }

    public static ArrayList<Photo> getMyPhotos(String myUid) throws ClientProtocolException, IOException, JSONException
    {
    	Log.w("WEYNAK.getmyphotos", "fetfiyaaaaaaaaaaaaa");
    	ArrayList<Photo> data = new ArrayList<Photo>();
    	HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(GET_MY_PHOTOS);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("uid", myUid));
        post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
        	
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            JSONObject json_data = null;
			for (int i = 0; i < result.length(); i++) {
				Photo p = new Photo();
				json_data = result.getJSONObject(i);
				p.uid = myUid;
				p.snapshot = json_data.getString("snapshot");
				p.fname = json_data.getString("fname");
				p.lname = json_data.getString("lname");
				p.lat = json_data.getDouble("latitude");
				p.lon = json_data.getDouble("longitude");
				p.date = json_data.getString("action_date");
				data.add(p);
				}
			
        }		
        return data;
    }
    
    public static ArrayList<Photo> getPhotos(String myUid) throws ClientProtocolException, IOException, JSONException
    {
    	Log.w("WEYNAK.getphotos", "fetfiyaaaaaaaaaaaaa");
    	ArrayList<Photo> data = new ArrayList<Photo>();
    	HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(GET_PHOTOS);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("uid", myUid));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
        	
            String res = EntityUtils.toString(response.getEntity());
            JSONArray result = new JSONArray(res);
            JSONObject json_data = null;
			for (int i = 0; i < result.length(); i++) {
				Photo p = new Photo();
				json_data = result.getJSONObject(i);
				p.snapshot = json_data.getString("snapshot");
				p.fname = json_data.getString("fname");
				p.lname = json_data.getString("lname");
				p.lat = json_data.getDouble("latitude");
				p.lon = json_data.getDouble("longitude");
				p.date = json_data.getString("action_date");
				data.add(p);
				}
        }		
        return data;
    }
    
    public static boolean update(String name, String uid, double lat, double lon, String act)
            throws ClientProtocolException, IOException, JSONException
    {
    	Calendar cal = Calendar.getInstance();
 		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 		String date =  sdf.format(cal.getTime());
        HttpClient client = new DefaultHttpClient(params);
        HttpPost post = new HttpPost(UPDATE_URI);
        List<NameValuePair> parameters = new ArrayList<NameValuePair>();
        parameters.add(new BasicNameValuePair("name", name));
        parameters.add(new BasicNameValuePair("uid", uid));
        parameters.add(new BasicNameValuePair("lat", Double.toString(lat)));
        parameters.add(new BasicNameValuePair("lon", Double.toString(lon)));
        parameters.add(new BasicNameValuePair("action", act));
        parameters.add(new BasicNameValuePair("action_d", date));
        post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
        HttpResponse response = client.execute(post);
        if (response.getStatusLine().getStatusCode() == 200) {
            
            return true;
        }
        else return false;
    }

    public static boolean RegisterPush(String uid, String name ,String registrationid)
    throws ClientProtocolException, IOException, JSONException
		{    	 	
    	 	Calendar cal = Calendar.getInstance();
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
			String date =  sdf.format(cal.getTime());
			HttpClient client = new DefaultHttpClient(params);
			HttpPost post = new HttpPost(REGISTER_PUSH);
			List<NameValuePair> parameters = new ArrayList<NameValuePair>();
			parameters.add(new BasicNameValuePair("name", name));
			parameters.add(new BasicNameValuePair("uid", uid));
			parameters.add(new BasicNameValuePair("token", registrationid));
			parameters.add(new BasicNameValuePair("date", date));
			post.setEntity(new UrlEncodedFormEntity(parameters, HTTP.UTF_8));
			HttpResponse response = client.execute(post);
			if (response.getStatusLine().getStatusCode() == 200) {
			    
			    return true;
			}
			else return false;
		}
    
   public static void insertDBNote(String title,String desc, String id, Location l){
    	
    	Calendar cal = Calendar.getInstance();
 		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
 		String date =  sdf.format(cal.getTime());
    	ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
    	nameValuePairs.add(new BasicNameValuePair("uid",id));
    	nameValuePairs.add(new BasicNameValuePair("title",title));
    	nameValuePairs.add(new BasicNameValuePair("description",desc));
    	nameValuePairs.add(new BasicNameValuePair("lat",String.valueOf(l.getLatitude())));
    	nameValuePairs.add(new BasicNameValuePair("lon",String.valueOf(l.getLongitude())));
    	nameValuePairs.add(new BasicNameValuePair("action_d",date));
    	try {
		    	HttpClient httpclient = new DefaultHttpClient();
		        HttpPost httppost = new HttpPost(SAVE_NOTE);
		        httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
		        HttpResponse response = httpclient.execute(httppost);
		        if(response.getStatusLine().getStatusCode()==200)
		        {
		        	Maps.utils.sendEmptyMessage(Maps.LOCATION_SAVED);
		        }
    	} 	
    		catch(Exception e){
	        Log.e("WEYNAK.insertDB.note", "Error in http connection "+e.toString());
	        
    	}
    		
    }
    
}
